﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;

namespace MovingChameLibrary.Models.TourPage
{
    public class TourScheduleGroup : CommonGroupModel<Schedule>
    {
        #region Constructors
        public TourScheduleGroup()
            : base(Constants.TourTimelineId, Constants.TourTimelineTitle, null)
        {
            Items.CollectionChanged += ItemsCollectionChanged;
        }

        public TourScheduleGroup(CustomObservableCollection<Schedule> items)
            : base(Constants.TourTimelineId, Constants.TourTimelineTitle, items)
        {
            Items.CollectionChanged += ItemsCollectionChanged;
        }
        #endregion

        #region Collection Change Handler
        private void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    if (e.NewStartingIndex < Constants.MaxItemsPerPage)
                    {
                        TopItems.Insert(e.NewStartingIndex, Items[e.NewStartingIndex]);
                        if (TopItems.Count > Constants.MaxItemsPerPage)
                        {
                            TopItems.RemoveAt(Constants.MaxItemsPerPage);
                        }
                    }
                    break;
                case NotifyCollectionChangedAction.Remove:
                    if (e.OldStartingIndex < Constants.MaxItemsPerPage)
                    {
                        TopItems.RemoveAt(e.OldStartingIndex);
                        if (Items.Count >= Constants.MaxItemsPerPage)
                        {
                            TopItems.Add(Items[Constants.MaxItemsPerPage - 1]);
                        }
                    }
                    break;
                case NotifyCollectionChangedAction.Replace:
                    if (e.OldStartingIndex < Constants.MaxItemsPerPage)
                    {
                        TopItems[e.OldStartingIndex] = Items[e.OldStartingIndex];
                    }
                    break;
                case NotifyCollectionChangedAction.Reset:
                    TopItems.Clear();
                    while (TopItems.Count < Items.Count && TopItems.Count < Constants.MaxItemsPerPage)
                    {
                        TopItems.Add(Items[TopItems.Count]);
                    }
                    break;
            }
        }
        #endregion

        #region Properties
        private CustomObservableCollection<Schedule> _topItems = new CustomObservableCollection<Schedule>();
        public CustomObservableCollection<Schedule> TopItems
        {
            get { return this._topItems; }
        }
        #endregion
    }
}